package com.jl.smartcard.ui;

import java.net.URL;

import org.eclipse.core.runtime.Platform;
import org.eclipse.equinox.app.IApplication;
import org.eclipse.equinox.app.IApplicationContext;
import org.eclipse.osgi.service.datalocation.Location;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.internal.WorkbenchPlugin;
import org.eclipse.wb.swt.SWTResourceManager;

import com.jl.smartcard.core.CorePluginRuntime;
import com.jl.smartcard.ui.dialog.PickWorkspaceDialog;

/**
 * This class controls all aspects of the application's execution
 */
@SuppressWarnings("restriction")
public class Application implements IApplication {

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.equinox.app.IApplication#start(org.eclipse.equinox.app.
	 * IApplicationContext)
	 */
	@Override
	public Object start(IApplicationContext context) throws Exception {
		Display display = PlatformUI.createDisplay();
		try {
			Location instance = Platform.getInstanceLocation();
			String ws = null;
			do {
				if (PickWorkspaceDialog.isRememberWorkspace()) {
					ws = PickWorkspaceDialog.getLastSetWorkspaceDirectory();
				} else {
					Shell splashShell = WorkbenchPlugin.getSplashShell(display);
					PickWorkspaceDialog dia = new PickWorkspaceDialog(splashShell, SWT.NONE);
					Object res = dia.open();
					if (res == null) {
						System.exit(0);
					} else {
						ws = (String) res;
					}
				}
				if(!instance.set(new URL("file", null, ws), true)){
					MessageBox msg = new MessageBox(new Shell(),SWT.ICON_INFORMATION);
					msg.setMessage("the location is in used,please select another!");
					msg.setText("Infomation");
					msg.open();
					ws = null;
				}
			} while (ws == null);
			CorePluginRuntime.setValue(CorePluginRuntime.WORKSPACE_ROOT, ws);
			int returnCode = PlatformUI.createAndRunWorkbench(display,
					new ApplicationWorkbenchAdvisor());
			if (returnCode == PlatformUI.RETURN_RESTART)
				return IApplication.EXIT_RESTART;
			else
				return IApplication.EXIT_OK;
		} finally {
			SWTResourceManager.dispose();
			Location instance = Platform.getInstanceLocation();
			if(instance.isLocked()){
				instance.release();
			}
			display.dispose();
		}

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.equinox.app.IApplication#stop()
	 */
	@Override
	public void stop() {
		if (!PlatformUI.isWorkbenchRunning())
			return;
		final IWorkbench workbench = PlatformUI.getWorkbench();
		final Display display = workbench.getDisplay();
		display.syncExec(new Runnable() {
			@Override
			public void run() {
				if (!display.isDisposed())
					workbench.close();
			}
		});
	}
}
